package com.back.config;

import cn.dev33.satoken.util.SaResult;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(value = ConstraintViolationException.class)
    public SaResult errorHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        if (!CollectionUtils.isEmpty(constraintViolations)) {
            StringBuilder stringBuilder = new StringBuilder();
            for (ConstraintViolation constraintViolation : constraintViolations) {
                stringBuilder.append(constraintViolation.getMessage()).append(",");
            }
            String errorMessage = stringBuilder.toString();
            return SaResult.error(errorMessage);
        }
        return SaResult.error(ex.getMessage());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public SaResult errorHandler(MethodArgumentNotValidException ex) {
        List<ObjectError> objectErrors = ex.getBindingResult().getAllErrors();
        if (!CollectionUtils.isEmpty(objectErrors)) {
            StringBuilder builder = new StringBuilder();
            for (ObjectError objectError : objectErrors) {
                builder.append(objectError.getDefaultMessage()).append(",");
            }
            String errorMessage = builder.toString();
            return SaResult.error(errorMessage);
        }
        return SaResult.error(ex.getMessage());
    }
}
